<template>
  <div>
    <div class="top">
      <div class="header">
        <div class="left-logo">

        </div>
        <div class="left-title">
          <h2 class="title">浩瀚科技</h2>
        </div>
      </div>
    </div>
   <div style="width: 1000px;margin: 10px auto">
     <a-steps :current="1" >
       <a-step v-for="(item,index) in steps" :status="item.status" :key="index+'step'">
         <!-- <span slot="title">Finished</span> -->
         <template #title>{{ item.title }}</template>
       </a-step>
     </a-steps>
   </div>
    <div>
      <a-form
          class="fromWidth"
          v-show="this.current===0"
          ref="formRef"
          name="custom-validation"
          :model="formState"
          :rules="rules"
          v-bind="layout"
          @finish="handleFinish"
          @validate="handleValidate">
        <a-form-item has-feedback label="邮箱" name="useremail">
          <a-input v-model:value="formState.useremail" autocomplete="off"/>
        </a-form-item>
        <a-form-item v-show:vlaue="showInput" has-feedback label="验证码" name="yzCode">
          <a-input v-model:value="formState.yzCode" autocomplete="off"/>
          <a-button type="primary" @click="submitCode">提交</a-button>
        </a-form-item>
        <a-form-item class="sendCode" v-show="showButton">
          <a-button type="primary" @click="onShow">发送验证码</a-button>
          <Vcode :show="isShow" @success="onSuccess" @close="onClose"/>
        </a-form-item>
      </a-form>
      <a-form
          class="register-form"
          v-show="this.current===1"
          ref="formRegisterRef"
          name="custom-validation"
          :model="registerUser"
          :rules="registerUserRules"
          v-bind="layout"
          @finish="handleFinish"
          @validate="handleValidate">
        <a-form-item has-feedback label="头像" name="userAva" style="margin-bottom: 10px">
          <upload style="float: left" @sendMsg="getSondata"></upload>
          <a-avatar style="width: 200px;height: 200px;float: left" :src=" registerUser.userAva" alt="avatar"/>
        </a-form-item>
        <a-form-item has-feedback label="昵称" name="userNick">
          <a-input v-model:value="registerUser.userNick" autocomplete="off"/>
        </a-form-item>
        <a-form-item has-feedback label="账号" name="userName">
          <a-input v-model:value="registerUser.userName" autocomplete="off"/>
        </a-form-item>
        <a-form-item has-feedback label="密码" name="userPassword">
          <a-input v-model:value="registerUser.userPassword" type="password" autocomplete="off"/>
        </a-form-item>
        <a-form-item has-feedback label="年龄" name="userAge">
          <a-input v-model:value="registerUser.userAge" autocomplete="off"/>
        </a-form-item>
        <a-form-item has-feedback label="性别" name="userSex">
          <a-cascader v-model:value="registerUser.userSex" :options="optionsSex" placeholder="选择你的性别:"/>
          <a-button @click="registerSubmit"> 注册</a-button>
        </a-form-item>
        <hr>
      </a-form>
      <div v-show="this.current===2" class="register-success">
        <h1>恭喜你,注册成功</h1>
        <a href="http://localhost:8080/login">返回登录</a>
      </div>
    </div>
  </div>
</template>

<script>
import upload from '@/components/register/uploadCPM'
import Vcode from "vue3-puzzle-vcode";
import {message} from 'ant-design-vue';
import {defineComponent, reactive, ref} from 'vue';
import Icon, {
  UserOutlined,
  SolutionOutlined,
  LoadingOutlined,
  SmileOutlined,
  SearchOutlined
} from '@ant-design/icons-vue';

export default {
  name: "register",
  components: {
    upload,
    Vcode,
    Icon,
    message,
    UserOutlined,
    SolutionOutlined,
    LoadingOutlined,
    SmileOutlined,
    SearchOutlined
  },
  methods: {
    registerSubmit() {
      this.checkRegisterForm().then(res => {
        if (res.errorFields === undefined) {
          let status = false
          this.$httpPost(`/user/checkExistsUserName?username=${this.registerUser.userName}`).then(res => {
            if (res.data.code == 0) {
              console.log("进来了")
              status = true
            }
            if (status) {
              this.registerUser.userSex = this.registerUser.userSex[0]
              this.$httpPost("user/register", this.registerUser).then(res => {
                if (res.data.code === 0) {
                  this.steps[this.current].status = 'finish'
                  this.current++
                } else {
                  message.warn("服务器繁忙...")
                }
              })
            } else {
              message.warn("账号已存在,请重新输入!")
            }
          })
        }
      })
    },
    getSondata(value) {
      console.log("收到孩子传过来的参数", value)
      this.registerUser.userAva = value;
    },
    submitCode() {
      if (this.formState.yzCode !== '' && this.formState.useremail !== '') {
        const obj = {"email": this.formState.useremail, "code": this.formState.yzCode}
        this.$httpPost('/user/email/checkCode', obj).then(res => {
          if (res.data.code === 0) {
            this.registerUser.userEmail = this.formState.useremail
            this.steps[this.current].status = 'finish'
            this.current++
          } else {
            message.error(res.data.msg)
          }
        })
      } else {
        message.error("请先验证")
      }
    },
    pre() {
      this.current--

    },
    next() {
      if (this.steps[this.current].status === 'finish') {
        this.current++
      } else {
        message.warn("请先完成当前认证")
      }
    },
    stepsChange(e) {
      console.log(e)
    },
    onShow() {
      if (this.formState.useremail != '') {
        this.isShow = true;
      } else {
        message.warn("请输入邮箱")
      }
    },
    onClose() {
      this.isShow = false
      //  发送邮箱
    },
    onSuccess() {
      let token = this.$localStorage.get("token");
      this.$httpPost(`/user/email/registerCode?email=${this.formState.useremail}`).then(res => {
        console.log(res.data)
        if (res.data.code === 0) {
          this.showInput = true
          this.showButton = false
          this.onClose()
          message.success('验证码发送成功,请注意查收');
        } else {
          this.onClose()
          message.error(res.data.msg)
        }
      })
    }
  },
  data() {
    return {
      current: 0,
      stepMark: 0,
      steps: [{title: "邮箱验证", status: 'finished'}, {title: "填写账号信息", status: 'wait'}, {title: "注册成功", status: 'wait'}],
      showButton: true,
      isShow: false,
      showInput: false
    }
  },
  setup() {
    const formRegisterRef = ref();
    const optionsSex = reactive([
      {
        value: "男",
        label: "男"
      },
      {
        value: "女",
        label: "女"
      },
    ])
    const formRef = ref();
    const formState = reactive({
      useremail: '',
      yzCode: '',
    });
    // 监听子组件传递过来的参数的函数
    let validatePass = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('请输入邮箱');
      } else {
        const szReg = /^[A-Za-z\d]+([-_.][A-Za-z\d]+)*@([A-Za-z\d]+[-.])+[A-Za-z\d]{2,5}$/;
        if (!szReg.test(value)) {
          message.error("请输入正确的邮箱")
        }
        if (formState.useremail !== '') {
          await formRef.value.validateFields('checkPass');
        }
        return Promise.resolve();
      }
    };

    let validatePass2 = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('请输入邮箱验证码');
      } else {
        return Promise.resolve();
      }
    };

    const rules = {
      useremail: [{
        required: true,
        validator: validatePass,
        trigger: 'change',
      }],
      yzCode: [{
        required: true,
        validator: validatePass2,
        trigger: 'change',
      }],
    };
    const layout = {
      labelCol: {
        span: 5,
      },
      wrapperCol: {
        span: 14,
      },
    };
    const handleFinish = values => {
    };

    const checkRegisterForm = async () => {
      try {
        return await formRegisterRef.value.validateFields()
      } catch (errorInfo) {
        return errorInfo
      }
    };
    const resetForm = () => {
      formRef.value.resetFields();
    };

    const handleValidate = (...args) => {
    };
    const registerUser = reactive({
      userAva: '',
      userNick: '',
      userName: '',
      userPassword: '',
      userEmail: '',
      userAge: '',
      userSex: ''
    });
    let userNickVaild = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('请输入昵称:');
      } else {
        if (value.length > 10) {
          return Promise.reject('昵称长度只能在1-10之间！');
        }
        return Promise.resolve();
      }
    };
    let userNameVaild = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('请输入账号:');
      } else {
        if (value.length < 5 || value.length > 10) {
          return Promise.reject('账号长度只能在1-10之间！');
        }

        return Promise.resolve();
      }
    };
    let userPasswordVaild = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('请输入你的密码:');
      } else {
        if (value.length < 5 || value.length > 11) {
          return Promise.reject('密码长度只能在1-11之间！');
        }
        return Promise.resolve();
      }
    };
    let userAgeVaild = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('年龄不能为空:');
      } else {
        if (value < 0 || value.length > 3) {
          return Promise.reject('年龄格式不规范,请重新输入！');
        }
        return Promise.resolve();
      }
    };
    let userSexValid = async (_rule, value) => {
      if (value === '') {
        return Promise.reject('性别不能为空:');
      } else {
        return Promise.resolve();
      }
    };

    const registerUserRules = {
      userNick: [{
        required: true,
        validator: userNickVaild,
        trigger: 'blur',
      }],
      userName: [{
        required: true,
        validator: userNameVaild,
        trigger: 'blur',
      }],
      userPassword: [{
        required: true,
        validator: userPasswordVaild,
        trigger: 'blur',
      }],
      userAge: [{
        required: true,
        validator: userAgeVaild,
        trigger: 'blur',
      }],
      userSex: [{
        required: true,
        validator: userSexValid,
        trigger: 'blur',
      }],
    };
    return {
      checkRegisterForm,
      formRegisterRef,
      optionsSex,
      registerUser,
      registerUserRules,
      formState,
      formRef,
      rules,
      layout,
      handleFinish,
      resetForm,
      handleValidate,
    };
  },
}
</script>

<style scoped>
.top {
  width: 100%;
  height: 100px;
  background-color: #B1D9FF;
}

.title {
  font-weight: bold;
  height: 100px;
  line-height: 100px;
  text-align: center;
}

.left-title {
  float: left;
  width: 200px;
  height: 100px;

}

.left-logo {
  float: left;
  width: 200px;
  height: 100px;
  background-image: url("http://localhost:9191/nvw51d0ea.jpg");
  background-repeat: no-repeat;
  background-size: auto;
  background-position: center;
}

.header {
  margin: 0 auto;
  width: 80%;
  height: 100px;
}

.register-success {
  width: 30%;
  margin: 0 auto;
  text-align: center;
}

.sendCode {
  position: absolute;
  left: 396px;
  top: 0;
  width: 103px;
  margin: 0 auto;
}

.register-form {
  width: 60%;
  margin: 20px auto;
}

.fromWidth {
  position: relative;
  width: 500px;
  margin: 50px auto;
}

@media only screen and (max-width: 600px) {
  .fromWidth {
    width: 14rem;
  }
}

.div-input {
  display: flex;
  justify-content: center;
}

.btn-a:hover {
  color: red;
}

.stepdiv {
  width: 60%;
}

a:hover {

  text-decoration: underline red;
}

.top-nav {
}

.div1 {
  height: 5rem;
}

.st0 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: #CDE6FF;
}

.st1 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: #B1D9FF;
}

.st2 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: #9FCFFF;
}

.st3 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_1_);
}

.st4 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_2_);
}

.st5 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_3_);
}

.st6 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_4_);
}

.st7 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_5_);
}

.st8 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_6_);
}

.st9 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_7_);
}

.st10 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#Arm-Right_1_);
}

.st11 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_8_);
}

.st12 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_9_);
}

.st13 {
  fill: url(#SVGID_10_);
}

.st14 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_11_);
}

.st15 {
  fill: url(#SVGID_12_);
}

.st16 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_13_);
}

.st17 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_14_);
}

.st18 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_15_);
}

.st19 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_16_);
}

.st20 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_17_);
}

.st21 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_18_);
}

.st22 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_19_);
}

.st23 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_20_);
}

.st24 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_21_);
}

.st25 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_22_);
}

.st26 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_23_);
}

.st27 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_24_);
}

.st28 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#Hand-Left_1_);
}

.st29 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_25_);
}

.st30 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_26_);
}

.st31 {
  fill-rule: evenodd;
  clip-rule: evenodd;
  fill: url(#SVGID_27_);
}
</style>
